package com.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.portal.entity.News;
import com.portal.entity.NewsCategory;
import com.portal.mapper.NewsCategoryMapper;
import com.portal.mapper.NewsMapper;
import com.portal.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻服务实现类
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
    
    @Autowired
    private NewsCategoryMapper categoryMapper;
    
    @Override
    public List<NewsCategory> getEnabledCategories() {
        LambdaQueryWrapper<NewsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NewsCategory::getEnabled, true)
               .orderByAsc(NewsCategory::getSort);
        return categoryMapper.selectList(wrapper);
    }
    
    @Override
    public Map<String, Object> getNewsList(Long categoryId, Integer page, Integer size, String keyword) {
        // 构建查询条件
        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(News::getEnabled, true);
        
        // 添加分类过滤
        if (categoryId != null) {
            wrapper.eq(News::getCategoryId, categoryId);
        }
        
        // 添加关键词搜索
        if (keyword != null && !keyword.trim().isEmpty()) {
            String trimmedKeyword = keyword.trim();
            wrapper.and(w -> w
                .like(News::getTitle, trimmedKeyword)
                .or()
                .like(News::getDescription, trimmedKeyword)
                .or()
                .like(News::getContent, trimmedKeyword)
                .or()
                // 添加对创建时间的模糊匹配
                .apply("DATE_FORMAT(create_time, '%Y-%m-%d') LIKE {0}", "%" + trimmedKeyword + "%")
                .or()
                // 添加对更新时间的模糊匹配
                .apply("DATE_FORMAT(update_time, '%Y-%m-%d') LIKE {0}", "%" + trimmedKeyword + "%")
            );
        }
        
        wrapper.orderByDesc(News::getCreateTime);

        // 分页查询
        Page<News> newsPage = new Page<>(page, size);
        page(newsPage, wrapper);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", newsPage.getTotal());
        result.put("list", newsPage.getRecords());

        return result;
    }
    
    @Override
    @Transactional
    public News getNewsDetail(Long id) {
        News news = getById(id);
        if (news != null && news.getContent() != null) {
            // 格式化内容，添加基本样式
            String content = news.getContent()
                .replaceAll("\n", "<br>")  // 处理换行
                .replaceAll("\\s{2,}", "&nbsp;&nbsp;");  // 处理空格
            news.setContent(content);
        }
        return news;
    }

    @Override
    public List<News> getLatestNews(Integer limit) {
        // 构建查询条件
        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(News::getEnabled, true)
               .orderByDesc(News::getCreateTime)
               .last("LIMIT " + limit);

        return list(wrapper);
    }

    @Override
    public Map<String, News> getAdjacentNews(Long id) {
        Map<String, News> result = new HashMap<>();
        
        // 获取当前新闻
        News currentNews = getById(id);
        if (currentNews == null) {
            return result;
        }

        // 获取上一篇新闻（创建时间小于当前新闻的最新一篇）
        LambdaQueryWrapper<News> prevWrapper = new LambdaQueryWrapper<>();
        prevWrapper.eq(News::getEnabled, true)
                  .lt(News::getCreateTime, currentNews.getCreateTime())
                  .orderByDesc(News::getCreateTime)
                  .last("LIMIT 1");
        News prevNews = getOne(prevWrapper);
        
        // 获取下一篇新闻（创建时间大于当前新闻的最早一篇）
        LambdaQueryWrapper<News> nextWrapper = new LambdaQueryWrapper<>();
        nextWrapper.eq(News::getEnabled, true)
                  .gt(News::getCreateTime, currentNews.getCreateTime())
                  .orderByAsc(News::getCreateTime)
                  .last("LIMIT 1");
        News nextNews = getOne(nextWrapper);

        result.put("prev", prevNews);
        result.put("next", nextNews);
        
        return result;
    }
} 